package com.hu.bgp.framework;

import java.util.Timer;
import java.util.TimerTask;

import com.hu.bgp.framework.clientapi.ClientToServerMessage;
import com.hu.bgp.framework.clientapi.ServerToClientMessage;
import com.hu.bgp.server.Player;
import com.hu.bgp.shared.MinimumPlayersReachedMessage;
import com.hu.bgp.shared.NewServerToClientMessageEvent;

import de.novanic.eventservice.service.registry.EventRegistryFactory;

/**
 * Implementeer een subklasse van deze klasse bij het schrijven van de
 * game-logica van een spelletje.
 * 
 * @author ejvos
 */
public abstract class Server implements ServerFacade
{
	protected GameContext gameContext;

	public Server(GameContext gameContext)
	{
		this.gameContext = gameContext;
	}

	public abstract void handleMessage(ClientToServerMessage message, Player fromPlayer);

	public abstract void playerJoined(Player player);

	public abstract void playerLeft(Player player);

	public abstract void playerRejoined(Player player);

	public abstract void start();

	protected void broadcastMessage(ServerToClientMessage message)
	{
		NewServerToClientMessageEvent event = new NewServerToClientMessageEvent(message);
		EventRegistryFactory.getInstance().getEventRegistry().addEvent(gameContext.getGameDomain(), event);
	}

	protected void broadcastMinimumPlayersReachedEvent()
	{
		System.out.println(String.format("Server.broadcastMinimumPlayersReachedEvent"));
		// FIXME
		// TODO dirty hack zodat event pas wordt verstuurd als de laatst
		// gejoinde client naar events gaat luisteren
//		try
//		{
//			Thread.sleep(2000);
//		}
//		catch (InterruptedException e)
//		{
//			// ignored
//		}
//		MinimumPlayersReachedEvent event = new MinimumPlayersReachedEvent();
//		EventRegistryFactory.getInstance().getEventRegistry().addEvent(gameContext.getGameDomain(), event);
		TimerTask task = new TimerTask()
		{
			public void run()
			{
				MinimumPlayersReachedMessage message = new MinimumPlayersReachedMessage();
				broadcastMessage(message);
				start();
			}
		};
		Timer timer = new Timer();
		timer.schedule(task, 2000);
	}
}
